<?php
namespace app\admin\controller\member;
use app\common\controller\Backend;
use think\Controller;
use think\Request;
use think\Lang;
use fast\Random;
use fast\Tree;
use fast\Cols;
use fast\Date;
use think\cache\Driver\File;
class Membergroup extends Backend{
		protected $model = null;//模型对象
		protected $columnlist = array();
		public function _initialize(){
				parent::_initialize();
				$this->model = model('Membergroup');
				$this->columnarry = Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/module.php','',1);
		}
		public function listforajax(){
				$lst = $this->model->order('itemid','desc')->select();
				print_r(json_encode($lst));
				exit;
		}
		public function add(){
				if ($this->request->isPost()){
						$params = $this->request->post("row/a");
						if ($params){
								$fc = new File();
								$this->modelValidate = false;
								if ($this->dataLimit){
										$params[$this->dataLimitField] = $this->auth->id;
								}
								try{
										//是否采用模型验证
										if ($this->modelValidate){
												$name = basename(str_replace('\\', '/', get_class($this->model)));
												$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
												$this->model->validate($validate);
										}
										$params['itemid'] = str_replace('-','',Random::uuid());
										$result = $this->model->allowField(true)->save($params);
										if ($result !== false){
												$this->success();
										}else{
												$this->error($this->model->getError());
										}
								}
								catch (\think\exception\PDOException $e){
										$this->error($e->getMessage());
								}
						}
						$this->error(__('Parameter %s can not be empty', ''));
				}else{
						$fc = new File();
						return $this->view->fetch();
				}
		}
		public function edit($ids = NULL){
				$row = $this->model->get($ids);$fc = new File();

				$id = $ids;
				if (!$row){$this->error(__('No Results were found'));}
				$adminIds = $this->getDataLimitAdminIds();
				if (is_array($adminIds)){
						if (!in_array($row[$this->dataLimitField], $adminIds)){
								$this->error(__('You have no permission'));
						}
				}
				if ($this->request->isPost()){
						$params = $this->request->post("row/a");
						if ($params){
								try{
										//是否采用模型验证
										if ($this->modelValidate){
												$name = basename(str_replace('\\', '/', get_class($this->model)));
												$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
												$row->validate($validate);
										}
										$result = $row->allowField(true)->save($params);
										if ($result !== false){$this->success();}
										else{$this->error($row->getError());}
								}
								catch (\think\exception\PDOException $e){
										$this->error($e->getMessage());
								}
						}
						$this->error(__('Parameter %s can not be empty', ''));
				}
				//print_r($ids);exit;
				$this->view->assign("ids",$id);
				$this->view->assign("row", $row);
				return $this->view->fetch();
		}
		public function index(){
				$columnlist = Cols::columnread('membergroup');
				$flag = array();$options = array();
				foreach($columnlist as $v){
						$flag[] = $v['listorder'];
						if($v['options']){
								//把带有选项的列，提取出来。
								$options[$v['columnenname']] = $v['options'];
						}
				}
				array_multisort($flag, SORT_ASC, $columnlist);
				//设置过滤方法
				$this->request->filter(['strip_tags']);
				//如果发送的来源是Selectpage，则转发到Selectpage
				if ($this->request->request('pkey_name')){
						return $this->selectpage();
				}
				$searchfileds = array();
				$searchfileds['name'] = 'varcharshort';
				list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
				$order = 'desc';
				$sort = 'itemid';
				$total = $this->model
				->where($where)
				->order($sort, $order)
				->count();
				$totalpage = 1;$page = 1;
				if($limit>0){
						$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
						//总页数
						if($offset>0){$page = intval($offset/$limit)+1;}
				}
				$list = $this->model
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
				for ($i = 0; $i < count($list); $i++) {
						if(isset($list[$i]['category'])){
								$list[$i]['catname'] = $list[$i]['category']['name'];
						}
						unset($list[$i]['intro']);unset($list[$i]['content']);
						foreach ($options as $k => $v) {
								if(isset($list[$i][$k])){
										$arj = json_decode($v,true);
										$sarj = $arj[$list[$i][$k]];
										$list[$i][$k] = $sarj;
								}
						}
						$list[$i]['createtime'] = Date::timetodate($list[$i]['createtime'],3);
				}
				$result = array("total" => $total, "rows" => $list);
				$this->view->assign("lists",$result['rows']);
				$this->view->assign("columnlist",$columnlist);
				$this->view->assign("total",$result['total']);
				$this->view->assign("offset",$offset);
				$this->view->assign("limit",$limit);
				$this->view->assign("totalpage",$totalpage);
				$this->view->assign("page",$page);
				return $this->view->fetch('index');
		}
		public function showlist(){
				$ids = $this->request->post('ids');
				$ischeck = $this->request->post('ischeck');
				model('Column')->where('itemid',$ids)->update(['isshowlist'=>($ischeck==='true'?1:0)]);
				$ll = model('Column')->getColumnsByModel('membergroup');
				$lls = array();
				foreach ($ll as $k => $v) {
						$lls[ucfirst($v['columnenname'])] = $v;
				}
				$string = "<?php return ".var_export($lls, true)."; ?>";
				$filename = COLUMN_PATH.DS.'membergroup.php';
				$result = file_put_contents($filename, $string);
				if(@$fp = fopen($filename,'wb')) {
						flock($fp, LOCK_EX);
						$len = fwrite($fp, $string);
						flock($fp, LOCK_UN);
						fclose($fp);
						echo $len;exit;
				} else {
						echo '失败了';exit;
				}
		}

		/**
     * 读取角色权限树
     *
     * @internal
     */
     public function roletree()
     {
         $this->loadlang('member/group');
         $model = model('MemberGroup');
         $id = $this->request->post("id");
         $pid = $this->request->post("pid");
         $parentGroupModel = $model->get($pid);
         $currentGroupModel = NULL;
         if ($id){
             $currentGroupModel = $model->get($id);
         }
				 $id = $id ? $id : NULL;
				 $ruleList = collection(model('MemberRule')->order('weigh', 'desc')->select())->toArray();
				 /*
				 //读取父类角色所有节点列表
				 $parentRuleList = [];
				 if (in_array('*', explode(',', $parentGroupModel->rules))){
						 $parentRuleList = $ruleList;
				 }else{
						 $parentRuleIds = explode(',', $parentGroupModel->rules);
						 foreach ($ruleList as $k => $v)
						 {
								 if (in_array($v['itemid'], $parentRuleIds))
								 {
										 $parentRuleList[] = $v;
								 }
						 }
				 }
				 */
				 //当前所有正常规则列表
				 Tree::instance()->init($ruleList);
				 //读取当前角色下规则ID集合
				 //$adminRuleIds = $this->auth->getRuleIds();
				 //是否是超级管理员
				 //$superadmin = $this->auth->isSuperAdmin();
				 //当前拥有的规则ID集合
				 $currentRuleIds = $id ? explode(',', $currentGroupModel->rules) : $ruleList;
				 $parentRuleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
				 $parentRuleIds = array_map(function($item) {
						 return $item['itemid'];
				 }, $parentRuleList);
				 $nodeList = [];
				 foreach ($parentRuleList as $k => $v){
						 // if (!$superadmin && !in_array($v['itemid'], $adminRuleIds))
							// 	 continue;
						 // if ($v['pid'] && !in_array($v['pid'], $parentRuleIds))
							// 	 continue;
						 $state = array('selected' => in_array($v['itemid'], $currentRuleIds));
						 $nodeList[] = array('id' => $v['itemid'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
				 }
				 $this->success('', null, $nodeList);
				 /*
				 if (!$id || !in_array($pid, Tree::instance()->getChildrenIds($id, TRUE)))
				 {
						 $parentRuleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
						 $hasChildrens = [];
						 foreach ($parentRuleList as $k => $v)
						 {
								 if ($v['haschild'])
										 $hasChildrens[] = $v['itemid'];
						 }
						 $parentRuleIds = array_map(function($item) {
								 return $item['itemid'];
						 }, $parentRuleList);
						 $nodeList = [];
						 foreach ($parentRuleList as $k => $v)
						 {
								 // if (!$superadmin && !in_array($v['itemid'], $adminRuleIds))
									// 	 continue;
								 if ($v['pid'] && !in_array($v['pid'], $parentRuleIds))
										 continue;
								 $state = array('selected' => in_array($v['itemid'], $currentRuleIds) && !in_array($v['itemid'], $hasChildrens));
								 $nodeList[] = array('id' => $v['itemid'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
						 }
						 $this->success('', null, $nodeList);
				 }
				 else{
						 $this->error(__('Can not change the parent to child'));
				 }

         if (($pid || $parentGroupModel) && (!$id || $currentGroupModel))
         {

         }
         else
         {
             $this->error(__('Group not found'));
         }
				 */
     }
}?>
